package com.mianle.userapi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * XML工具类
 */
public class XMLUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(XMLUtils.class);

    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
           
        }
        return null;
    }
	
	public static void main(String[] args) throws Exception {
		String response = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg><appid><![CDATA[wx8cb4511f821ff6f4]]></appid><mch_id><![CDATA[1499647912]]></mch_id><nonce_str><![CDATA[GUZhLd8texomDNZY]]></nonce_str><sign><![CDATA[6DC460383B2B00510A370A9E01A4CFA6]]></sign><result_code><![CDATA[SUCCESS]]></result_code><prepay_id><![CDATA[wx2018033022301346d9eb8b370319654126]]></prepay_id><trade_type><![CDATA[NATIVE]]></trade_type><code_url><![CDATA[weixin://wxpay/bizpayurl?pr=EKhmoIM]]></code_url></xml>";
		Map<String, String> map = xmlToMap(response);
		System.out.println(JsonUtil.object2Json(map));
	}
	
}